<template>
  <div>
    <cube-form
      :model="model"
      :schema="schema"
      @submit="submitHandler"
    ></cube-form>
  </div>
</template>
<script>
export default {
  data() {
    return {
      model: {
        username: "",
        password: "",
      },
      schema: {
        fields: [
          {
            //这是一个input框
            type: "input",
            //modelKey的属性要与model下的username一致
            modelKey: "username",
            label: "用户名",
            props: {
              placeholder: "请输入用户名",
            },
            rules: {
              required: true,

              min: 3,
              max: 15,
            },
            trigger: "blur",
            //不满足相对应的条件时所提示的信息
            messages: {
              required: "用户名不能为空",
              min: "用户名不能少于3个字府",
              max: "用户名不能大于15个字符",
            },
          },
          {
            type: "input",
            modelKey: "password",
            label: "请输入密码",
            props: {
              placeholder: "请输入密码",
              type: "password",
              //密码框特有的小眼睛
              eye: {
                open: true,
                reverse: true,
              },
            },
            rules: {
              required: true,
              min: 3,
              max: 15,
            },
            //鼠标失去焦点就触发
            trigger: "blur",
            messages: {
              required: "用户名不能为空",
              min: "用户名不能少于3个字府",
              max: "用户名不能大于15个字符",
            },
          },
          //添加一个提交框
          {
            type: "submit",
            label: "Submit",
          },
        ],
      },
    };
  },
  methods: {
    submitHandler(e) {
      e.preventDefault();

      //改变this指向，同理箭头函数也可实现
      // const _this = this;
      //Axios is a promise-based HTTP Client、
      //get请求下,进行处理
      this.$http.getRequest("https://www.fastmock.site/mock/cd3d5761d593faad7e37ece0c50af664/api/login", {
          params: this.model,
        }).then(res=>{
          const userList=res.data;
          let loginlength= userList.filter(e=>e.username===this.model.username&&e.password===this.model.password).length;
          if(loginlength>0){
          let  token=this.model.username+'-'+this.model.password+'-'+(new Date().getTime()+60*60*1000)
           //一旦登录就设置token，保存在sessionStorage和store中，
           window.sessionStorage.setItem('token',token),
            this.$store.commit('setToken',token)

            //如果是因为token过期之类的重回登录页，登录之后直接返回之前访问的路由
           let authRouter=this.$route.query.redirect

            if(authRouter){
              this.$router.replace(
                authRouter
                );
            }else{
                this.$router.replace('/botNav/home');
            } 
          }
          else{
            ''('密码错误');
          }
        }
        )
        .catch(function (error) {
          ''(error);
        });
    },
  },
};
</script>

<style lang="stylus" scoped></style>